package cn.itcast.mq.amqp;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.HashMap;
import java.util.Map;

/**
 * SpringAMQP写法：生产者
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class AmqpPublisher {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 1.HelloWorld案例发送1条消息
     */
    @Test
    public void sendMSG_HelloWorld(){
        String queneName = "simple.queue";//队列名称
        String msg = "HelloWorld！！！";//消息
        rabbitTemplate.convertAndSend(queneName,msg);
    }

    /**
     * 2.Work模式发送多条消息,消费端由2个Listener进行消息的消费
     */
    @Test
    public void sendMSG_Work(){
        String queneName = "simple.queue";//队列名称
        for (int i = 1; i <= 50; i++) {
            String msg = "发送的第"+i+"条数据。";//消息
            rabbitTemplate.convertAndSend(queneName,msg);
        }
        System.out.println("发送消息到：simple.queue队列中完毕。");
    }

    /**
     * 3.FanoutExchange模式：路由key为""
     * fanout.exchange绑定了2个队列：fanout.queue1和fanout.queue2
     */
    @Test
    public void sendMSG_FanoutExchange(){
        String exchangeName = "fanout.exchange";//交换机名称
        String routingKey = "";//路由key
        String msg = "fanout模式发送的消息。";//消息
        rabbitTemplate.convertAndSend(exchangeName,routingKey,msg);
    }

    /**
     * 4.DirectExchange模式：可以指定路由key
     */
    @Test
    public void sendMSG_DirectExchange(){
        String exchangeName = "direct.exchange";//交换机名称
        String routingKey = "key1";
        String msg = "direct模式发送的消息。";//消息
        //与交换机direct.exchange绑定关系,且路由key为key1的队列,能够收到消息
        rabbitTemplate.convertAndSend(exchangeName,routingKey,msg);
    }

    /**
     * 5.TopicExchange模式：可以指定路由key模糊匹配,如:
     * china.#   china.*
     * #：代表0个或多个单词
     * *：代表1个单词
     */
    @Test
    public void sendMSG_TopicExchange(){
        String exchangeName = "topic.exchange";//交换机名称
        //String routingKey = "china.111.222";//routingKey="china.#"的队列能接受到消息
        String routingKey = "china.111";//routingKey="china.*"和routingKey="china.#的队列都能接受到消息
        String msg = "topic模式发送的消息。";//消息
        //与交换机topic.exchange绑定关系,且路由key为模糊匹配,相应的队列,能够收到消息
        rabbitTemplate.convertAndSend(exchangeName,routingKey,msg);
    }

    /**
     * 6.发送object类型的数据
     */
    @Test
    public void sendMSG_Object(){
        String exchangeName = "object.exchange";//交换机名称
        String routingKey = "";//
        Map<String,Object> msg = new HashMap<>();
        msg.put("name","吴佳威");
        msg.put("age",18);
        msg.put("sex","男");
        //与交换机object.exchange绑定关系,
        rabbitTemplate.convertAndSend(exchangeName,routingKey,msg);
    }
}
